import 'package:flutter/material.dart';

import 'beans/listbyorg_bean.dart';
import 'beans/onelist_bean.dart';
import 'const.dart';
import 'utils/mydio.dart';
import 'view/loading.dart';

class ListPage extends StatefulWidget {
  final String type;
  final int titleIndex;
  final int page;

  ListPage({String type, String titleIndex, String page})
      : this.type = type,
        this.titleIndex = int.parse(titleIndex),
        this.page = int.parse(page);

  @override
  State<StatefulWidget> createState() =>
      ListState(type: type, titleIndex: titleIndex, page: page);
}

class ListState extends State<ListPage> {
  var loadingDialog;
  String type;
  int titleIndex;
  int page;
  bool unShow = false;
  ScrollController _scrollController = ScrollController(); //listview的控制器
  bool isLoading = false; //是否正在加载数据
  var items = List();

  var id2, id3;

  ListState({String type, int titleIndex, int page})
      : this.titleIndex = titleIndex,
        this.type = type,
        this.page = page;

  _showDialog() {
    loadingDialog = LoadingDialog(
      text: '加载中...',
    );
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return loadingDialog;
        });
  }

  List<Widget> doWidgets() {
    List<Widget> listTitles = List();
    for (var i = 0; i < items.length; i++) {
      listTitles.add(buildListItem(context, items[i]));
    }
    return listTitles;
  }

  Widget buildListItem(BuildContext context, var bean) {
    return GestureDetector(
      onTap: () {
        page++;
        if (page == 2) {}
        switch (page) {
          case 1:
            if (type == Const.COMPANYS) {
              _showDialog();
              id2 = bean.id;

              _twolist(id2);
            }
            break;
          case 2:
            if (type == Const.COMPANYS) {
              _showDialog();
              id3 = bean.id;
              _listByOrganiz(id3);
            }
            break;
        }

        print('id2:$id2,id3:$id3');
      },
      child: Card(
        color: Colors.transparent,
        elevation: 0,
        child: Container(
          padding: const EdgeInsets.fromLTRB(20, 13, 20, 13),
          child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Offstage(
                      offstage: unShow,
                      child: ImageIcon(
                        AssetImage('images/icon_leixing chengshi.png'),
                        color: const Color(0xff23AFDC),
                        size: 24,
                      ),
                    ),
                    SizedBox(width: 10.0),
                    SizedBox(
                      width: unShow ? 310 : 260,
                      child: Text(
                        bean.name,
                        softWrap: false,
                        style: TextStyle(
                            fontSize: 16.0, color: const Color(0xFF333333)),
                      ),
                    ),
                  ],
                ),
                Text(
                  unShow ? '' : bean.count.toString(),
                  style:
                      TextStyle(fontSize: 16.0, color: const Color(0xFF333333)),
                ),
              ]),
        ),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    if (type == Const.COMPANYS) {
      _onelist();
    }

//    _scrollController.addListener(() {
//      if (_scrollController.position.pixels ==
//          _scrollController.position.maxScrollExtent) {
//        print('滑动到了最底部');
//        // _getMore();
//      }
//    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(Const.TITLES_UP[titleIndex]),
          centerTitle: true,
          backgroundColor: Color(0xff23AFDC),
          leading: IconButton(
              icon: Icon(Icons.arrow_back_ios),
              onPressed: () {
                if (page == 0) {
                  Navigator.pop(context);
                  return;
                }
                page--;
                setState(() {
                  _getList(page);
                });
              }),
          elevation: 0.0,
        ),
        body: RefreshIndicator(
          onRefresh: _onRefresh,
          child: ListView.builder(
//            controller: _scrollController,
            itemCount: items == null ? 0 : items.length,
            itemBuilder: _renderRow,
          ),
        ));
  }

  Future<Null> _onRefresh() async {
    await _getList(page);
    return;
  }

  _getList(int page) {
    _showDialog();
    switch (page) {
      case 0:
        if (type == Const.COMPANYS) {
          _onelist();
        }
        break;
      case 1:
        if (type == Const.COMPANYS) {
          _twolist(id2);
        }
        break;
      case 2:
        if (type == Const.COMPANYS) {
          _listByOrganiz(id3);
        }
        break;
    }
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < items.length) {
      return doWidgets()[index];
    }
//    return _getMoreWidget();
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              '加载中...',
              style: TextStyle(fontSize: 16.0),
            ),
            CircularProgressIndicator(
              strokeWidth: 1.0,
            )
          ],
        ),
      ),
    );
  }

  intentMe(int titleIndex) async {
    page++;
  }

  // 驾培机构 1
  _onelist() {
    MyDio.getInstance().get(
      '/api/bussSch/onelist',
      (data) {
        if (loadingDialog != null) {
          loadingDialog = null;
          Navigator.pop(context);
        }
        items.clear();
        for (var s in data) {
          items.add(OnelistBean.fromJson(s));
        }
        setState(() {
          unShow = false;
        });
      },
    );
  }

// 驾培机构 2
  _twolist(String id) {
    Map data = Map<String, dynamic>();
    data["id"] = id;
    MyDio.getInstance().get('/api/bussSch/twolist', (data) {
      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
      items.clear();
      for (var s in data) {
        items.add(OnelistBean.fromJson(s));
      }
      setState(() {
        unShow = false;
      });
    }, params: data);
  }

  // 驾培机构 3
  _listByOrganiz(String id) {
    Map data = Map<String, dynamic>();
    data["organiz"] = id;
    MyDio.getInstance().get('/api/bussSch/twolist', (data) {
      print('data:$data');
      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }
      items.clear();
      for (var s in data) {
        items.add(ListbyorgBean.fromJson(s));
      }
      setState(() {
        unShow = unShow = true;
      });
    }, params: data);
  }

// 驾培机构 3
//  Future<Null> _listByOrganiz(String id) async {
//    Map data = Map<String, dynamic>();
//    data["organiz"] = id;
//    try {
//      // flutter packages pub run build_runner build
//      Dio dio = Dio(Const.get);
//      print(dio.options.method);
//      Response response = await dio.request('/api/bussSch/listByOrganiz',
//          queryParameters: data);
//
//      if (loadingDialog != null) {
//        loadingDialog = null;
//        Navigator.pop(context);
//      }
//
//      Map<String, dynamic> decoded = json.decode(response.toString());
//      print('response:$response');
//      ListbyorgBean listbyorgBean = ListbyorgBean.fromJson(decoded);
//
//      setState(() {
//        unShow = true;
//        items = listbyorgBean.data;
//      });
//    } catch (e) {
//      print(e);
//    }
//  }
}
